package com.unicom.room.controller;


import com.alibaba.fastjson.JSONObject;
import com.unicom.room.common.JsonResult;
import com.unicom.room.model.User;
import com.unicom.room.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import java.util.ArrayList;
import java.util.List;



@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/getUserInfo")
    @ResponseBody
    public List<User> getUserInfo(HttpServletRequest request) {
      //先判断是超级管理员还是普通管理员
        HttpSession session = request.getSession();
        String name=(String)session.getAttribute("name");
        logger.info("登陆人员为："+name);
        //查此用户对应的类型
        User user=userService.selectByUsername(name);
        List<User> userList=new ArrayList<>();
        if(0== user.getUserType()) {
            //查出所有管理员信息
           userList = userService.getAllUserInfo();
            if (userList != null) {
                logger.info("管理人员个数:" + userList.size());
            }
        }else{
            //只查出普通管理员的信息
            userList = userService.getUserInfo();
            if (userList != null) {
                logger.info("管理人员个数:" + userList.size());
            }
        }
        return userList;
    }

    //登录处理
    @PostMapping(value = "/login")
    @ResponseBody
    public JsonResult login(@RequestBody JSONObject object, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        String name = object.getString("name");
        String password = object.getString("password");
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        HttpSession session = request.getSession();
        session.setAttribute("name",name);
        session.setAttribute("token", token);

        String name1=(String)session.getAttribute("name");
        logger.info("登陆人员为："+name1);

        try {
            subject.login(token);
            User user = userService.selectByUsername(name);
            user.setPassword("");
            if (subject.hasRole("0")) {
                return new JsonResult("00000", name + "登陆成功", user);
            } else if (subject.hasRole("1")) {
                return new JsonResult("00000", name + "登陆成功", user);
            } else {
                return new JsonResult("500", "未知用户登陆成功");
            }
        } catch (AuthenticationException e) {
            return new JsonResult("500", "鉴权失败，用户名或密码错误");
        }
    }

    //退出登录
    @GetMapping("/logout")
    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("token");
        SecurityUtils.getSubject().logout();
    }
    @GetMapping("/noLogin")
    @ResponseBody
    public  JsonResult noLogin() {
        return new JsonResult("200", "未登录");
    }

    //超级管理员新增普通管理员
    @RequestMapping(value = "/insertManager", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult insertManager(User user) {
        try {
            //打印出新增人员名字
            logger.info("user.getName():" + user.getName());

            //先查询是否存在此普通管理员，若无此用户才添加
            if (null == userService.selectByUsername(user.getName())) {
                //没查到此用户,进行添加
                int flag = userService.insertUser(user);
                if (1 == flag) {
                    return new JsonResult("00000", "新增管理员成功");
                } else {
                    return new JsonResult("500", "新增管理员失败");
                }
            } else {
                //已存在此人，不用添加
                return new JsonResult("500", "此用户已存在");
            }
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }
    //修改管理员信息
    @RequestMapping(value="/updateManager",method=RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateUser(@RequestBody User  user){
        //打印要修改的人名
        logger.info("user.getName():" + user.getName());
        try{
        if (1 == userService.updateUser(user)) {
            return new JsonResult("00000", "修改管理员信息成功");
        } else {
            return new JsonResult("500", "修改管理员信息失败");
        }
    } catch (Exception e) {
        return new JsonResult("500", e.getMessage());
    }
}

    //超级管理员删除普通管理员
    @RequestMapping(value = "/deleteManager/{name}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteManager(@PathVariable("name") String name) {
        try {
            //要删除的人名为
            logger.info("user.getName():" + name);
            if (1 == userService.deleteUser(name)) {
                return new JsonResult("00000", "删除管理员成功");
            } else {
                return new JsonResult("500", "删除管理员失败");
            }
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }



}